/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.reactivex.rxjava3.openharmony.schedulers;

import io.reactivex.rxjava3.core.Scheduler;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.openharmony.util.LogUtil;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;

import java.util.concurrent.TimeUnit;

import ohos.eventhandler.EventHandler;

final class HandlerScheduler extends Scheduler {
    private static final String TAG = "HandlerScheduler";
    private final EventHandler eventhandler;
    private final boolean async;

    HandlerScheduler(EventHandler eventhandler, boolean async) {
        this.eventhandler = eventhandler;
        this.async = async;
    }

    @Override
    public Disposable scheduleDirect(Runnable run, long delay, TimeUnit unit) {
        if (run == null) {
            throw new NullPointerException("run == null");
        }
        if (unit == null) {
            throw new NullPointerException("unit == null");
        }

        Runnable scheduledRun = RxJavaPlugins.onSchedule(run);
        ScheduledRunnable scheduled = new ScheduledRunnable(eventhandler, scheduledRun);

        eventhandler.postTask(scheduled, unit.toMillis(delay)); // This will delay calling run after that many ms
        return scheduled;
    }

    @Override
    public Worker createWorker() {
        return new HandlerWorker(eventhandler, async);
    }

    private static final class HandlerWorker extends Worker {
        private final EventHandler eventhandler;
        private final boolean async;

        private volatile boolean disposed;

        private ScheduledRunnable scheduled = null;

        HandlerWorker(EventHandler eventhandler, boolean async) {
            this.eventhandler = eventhandler;
            this.async = async;
        }

        @Override
        public Disposable schedule(Runnable run, long delay, TimeUnit unit) {
            if (run == null) {
                throw new NullPointerException("run == null");
            }
            if (unit == null) {
                throw new NullPointerException("unit == null");
            }
            if (disposed) {
                return Disposable.disposed();
            }
            Runnable scheduledRun = RxJavaPlugins.onSchedule(run);
            scheduled = new ScheduledRunnable(eventhandler, scheduledRun);
            eventhandler.postTask(scheduled, unit.toMillis(delay)); // this will delay calling run after that many ms
            // Re-check disposed state for removing in case we were racing a call to dispose().
            if (disposed) {
                eventhandler.removeAllEvent();
                return Disposable.disposed();
            }
            return scheduled;
        }

        @Override
        public void dispose() {
            LogUtil.info(TAG, "HandlerWorker dispose()");
            disposed = true;
            eventhandler.removeTask(scheduled);
        }

        @Override
        public boolean isDisposed() {
            return disposed;
        }
    }

    private static final class ScheduledRunnable implements Runnable, Disposable {
        private final EventHandler eventhandler;
        private final Runnable delegate;

        private volatile boolean disposed; // Tracked solely for isDisposed().

        ScheduledRunnable(EventHandler eventhandler, Runnable delegate) {
            this.eventhandler = eventhandler;
            this.delegate = delegate;
        }

        @Override
        public void run() {
            delegate.run();
        }

        @Override
        public void dispose() {
            LogUtil.info(TAG, "ScheduledRunnable dispose()");
            eventhandler.removeTask(this);
            disposed = true;
        }

        @Override
        public boolean isDisposed() {
            return disposed;
        }
    }
}
